package com.kalvin.kvf.modules.dy.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kalvin.kvf.modules.dy.entity.DyCookie;
import com.kalvin.kvf.modules.dy.mapper.DyCookieMapper;
import com.kalvin.kvf.modules.hxy.entity.Port;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.kalvin.kvf.modules.dy.entity.LoginUser;
import com.kalvin.kvf.modules.dy.mapper.LoginUserMapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 服务端登录抖音账号 服务实现类
 * </p>
 *
 * @since 2023-10-23 10:45:07
 */
@Service
public class LoginUserServiceImpl extends ServiceImpl<LoginUserMapper, LoginUser> implements LoginUserService {

    @Autowired
    private LoginUserMapper loginUserMapper;

    @Autowired
    private DyCookieMapper dyCookieMapper;


    /**
     * 获取登录信息的cookie
     *
     * @return
     * @throws Exception
     */
    @Transactional
    public int dyGetLoginCookies() throws Exception {
        //使用dos打开一个浏览器窗口
        Runtime.getRuntime().exec("C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe --remote-debugging-port=9520 --user-data-dir=\"E:\\chrome9520\"");
        ChromeOptions chromeOptions = new ChromeOptions();
        chromeOptions.setExperimentalOption("debuggerAddress", "localhost:9520");
        //使用webDriver去连接已经打开的浏览器
        WebDriver driver = new ChromeDriver(chromeOptions);

        driver.get("https://www.douyin.com/");
        //删除上次登录信息
        //driver.manage().deleteAllCookies();
        //刷新使退出登录有效
        //driver.navigate().refresh();
        //Thread.sleep(1000);

        //打开抖音 去登陆
        driver.get("https://www.douyin.com/");
        Thread.sleep(10000);

        //抖音个人信息主页
        String url = "https://www.douyin.com/user/self";
        driver.get(url);
        //休眠10秒 等待网页加载完成
        Thread.sleep(5000);

        //抖音号
        WebElement aH7rLkZZ = driver.findElement(By.className("TVGQz3SI"));
        String dyAccountNumber = aH7rLkZZ.getText().substring(4);
        //抖音头像
        WebElement pbpHcHqa = driver.findElement(By.className("BhdsqJgJ"));
        String dyHeadImgUrl = pbpHcHqa.getAttribute("src");
        //抖音网名
        WebElement nu66P_ba_pinglun = driver.findElement(By.className("j5WZzJdp"));
        WebElement span = nu66P_ba_pinglun.findElement(By.cssSelector("span span span span"));
        String dyNickName = span.getText();
        //去除cookie内 空name
        driver.manage().deleteCookieNamed("");
        //抖音登录的cookie
        Set<Cookie> cookies = driver.manage().getCookies();
        //休眠10秒 等待网页加载完成
        Thread.sleep(10000);

        //根据抖音号去库里查询是否有该用户
        QueryWrapper<LoginUser> loginUserWrapper = new QueryWrapper<>();
        loginUserWrapper.lambda().eq(LoginUser::getAccountNumber, dyAccountNumber);
        LoginUser loginuser = loginUserMapper.selectOne(loginUserWrapper);

        //有该用户 则删除用户信息以及对应cookie信息
        if (!StringUtils.isEmpty(loginuser)) {
            Long loginUserId = loginuser.getId();
            loginUserMapper.deleteById(loginUserId);
            QueryWrapper<DyCookie> dyCookieWrapper = new QueryWrapper<>();
            dyCookieWrapper.lambda().eq(DyCookie::getLoginUserId, loginUserId);
            dyCookieMapper.delete(dyCookieWrapper);
        }

        try {
            //当前抖音登录账号信息
            LoginUser loginUser = new LoginUser();
            loginUser.setNickName(dyNickName);
            loginUser.setAccountNumber(dyAccountNumber);
            loginUser.setHeadImgUrl(dyHeadImgUrl);
            loginUser.setIsLogin(0);
            loginUser.setLastLoginTime(LocalDateTime.now());
            loginUser.setCreateTime(LocalDateTime.now());
            //保存到数据库
            loginUserMapper.insert(loginUser);

            //抖音登录账号表自增长id
            Long loginUserId = loginUserMapper.getMaxId();
            //当前抖音登录cookie
            for (Cookie s : cookies) {
                DyCookie dyCookie = new DyCookie();
                if (s.getName() != null || !Objects.equals(s.getName(), "") ||
                        s.getValue() != null || !Objects.equals(s.getValue(), "")) {
                    dyCookie.setName(s.getName());
                    dyCookie.setValue(s.getValue());
                    dyCookie.setLoginUserId(loginUserId);
                    //保存数据库
                    dyCookieMapper.insert(dyCookie);
                }
            }
        } catch (Exception e) {
            //捕获异常的同时 事物不会失效
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            //关闭浏览器窗口
            driver.close();
            return -1;
        }
        //关闭浏览器窗口
        driver.quit();
        return 0;
    }


    /**
     * 删除抖音登录数据和cookie数据
     *
     * @param id
     * @return
     */
    public int delUserAndCookie(Long id) {
        try {
            loginUserMapper.deleteById(id);
            QueryWrapper<DyCookie> dyCookieWrapper = new QueryWrapper<>();
            dyCookieWrapper.lambda().eq(DyCookie::getLoginUserId, id);
            dyCookieMapper.delete(dyCookieWrapper);
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
        return 0;
    }


    /**
     * 使用cookie登录，1.未登录  2.距上次登录时间最长的一个
     *
     * @return
     */
    public Map<String,Object> useCookiesLogin(Port port,LoginUser loginUser2) throws Exception{
        Map<String,Object> map = new HashMap<>();
        //使用dos打开一个浏览器窗口
        Runtime.getRuntime().exec(" C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe --remote-debugging-port="+port.getPort()+" --user-data-dir=\"D:\\chrome"+port.getPort()+"\"");


        //System.getProperties().setProperty("webdriver.chrome.driver", "C:\\Program Files\\Google\\Chrome\\Application\\chromedriver.exe");
        ChromeOptions chromeOptions = new ChromeOptions();
        chromeOptions.setExperimentalOption("debuggerAddress", "localhost:"+port.getPort());
        //使用webDriver去连接已经打开的浏览器
        WebDriver driver = new ChromeDriver(chromeOptions);
        driver.get("https://www.douyin.com/");
        Thread.sleep(5000);
        //删除上次登录信息
        driver.manage().deleteAllCookies();
        Thread.sleep(5000);
        driver.navigate().refresh();
        //获取抖音账户数据
//        QueryWrapper<LoginUser> userWrapper = new QueryWrapper<>();
//        userWrapper.lambda().eq(LoginUser::getIsLogin, 0);
//        userWrapper.lambda().orderByAsc(LoginUser::getLastLoginTime);
//        userWrapper.last("limit 1");
//        LoginUser loginUser = loginUserMapper.selectOne(userWrapper);

        //没有查到用户信息则返回null
//        if (StringUtils.isEmpty(loginUser)) {
//            map.put("code",-1);
//            map.put("msg","没有可用的登录信息!");
//           return map;
//        }
        //用户登录状态   0：未登录  1：登陆中
        //Integer isLogin = loginUser.getIsLogin();

        //获取账号cookies
        QueryWrapper<DyCookie> cookieWrapper = new QueryWrapper<>();
        cookieWrapper.lambda().eq(DyCookie::getLoginUserId, loginUser2.getId());
        List<DyCookie> dyCookies = dyCookieMapper.selectList(cookieWrapper);

        //使用cookies登录
        try {
            for (DyCookie cookie : dyCookies) {
                if (!StringUtils.isEmpty(cookie.getName()) && !StringUtils.isEmpty(cookie.getValue())) {
                    Cookie ck = new Cookie(cookie.getName(), cookie.getValue());
                    driver.manage().addCookie(ck);
                }
            }
            Thread.sleep(5000);
            //刷新使登录有效
            driver.navigate().refresh();
            Thread.sleep(5000);
        }catch (Exception e){
            e.printStackTrace();
            map.put("code",-1);
            map.put("msg","登陆失败!");
            return map;
        }

        //修改该抖音用户的登录状态  为  登陆中
//        loginUser.setIsLogin(isLogin == 0 ? 1 : 0);
//        //更新上次登录时间
//        loginUser.setLastLoginTime(LocalDateTime.now());
//        loginUserMapper.updateById(loginUser);
        //抖音号
        String accountNumber = loginUser2.getAccountNumber();

        map.put("code",0);
        map.put("msg",accountNumber);
        map.put("driver",driver);
        return map;
    }


    @Override
    public Page<LoginUser> listLoginUserPage(LoginUser loginUser) {
        Page<LoginUser> page = new Page<>(loginUser.getCurrent(), loginUser.getSize());
        List<LoginUser> loginUsers = baseMapper.selectLoginUserList(loginUser, page);
        return page.setRecords(loginUsers);
    }








}
